﻿using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;

using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.PeteBrown;
using PeteBrown.MidiUtilities;

namespace Gadgeteer.MidiPerformanceTest
{
    public partial class Program
    {
        MidiModule midi = new MidiModule(11);

        private byte _note = MidiUtility.A440NoteNumber;
        private byte _velocity = 127;
        private MidiChannel _channel = MidiChannel.Channel01;

        private long _startingTicks;

        void ProgramStarted()
        {
            Debug.Print("Program Started");

            midi.MessageReceived += midi_MessageReceived;
            //midi.MessageReceived = midi_MessageReceived;

            midi.EnableReceiver();
            midi.DebugPrintEnabled = false;
            midi.AutoFlushSerialOutput = false;

            // send first message. remaining ones happen in handler

            Debug.Print("Sending first message.");
            _startingTicks = DateTime.Now.Ticks;
            Debug.Print("Starting ticks " + _startingTicks);
            midi.SendNoteOn(_channel, _note, _velocity);
        }


        private int _numCorrect = 0;
        private int _numErrors = 0;

        private const int _iterations = 100;

        private long _totalSendTicks = 0;

        void midi_MessageReceived(MidiModule sender, MidiMessage message)
        {
            if ((message.Channel == _channel) &&
                (message.DataByte1 == _note) &&
                (message.DataByte2 == _velocity))
                _numCorrect++;
            else
                _numErrors++;

            if (_numCorrect + _numErrors < _iterations)
            {
                //Debug.Print("Sending next message.");
                // send next message
                long startSending = DateTime.Now.Ticks;
                midi.SendNoteOn(_channel, _note, _velocity);
                _totalSendTicks += (DateTime.Now.Ticks - startSending);
            }
            else
            {
                long endingTicks = DateTime.Now.Ticks;
                long elapsedTicks = endingTicks - _startingTicks;

                Debug.Print("Correct: " + _numCorrect + ", Errors: " + _numErrors);
                Debug.Print("Ending ticks " + endingTicks);
                Debug.Print("Ticks per iteration " + ((double)elapsedTicks / _iterations));
                Debug.Print("** Total elapsed ticks " + elapsedTicks);
                Debug.Print("** Total send ticks " + _totalSendTicks);
                Debug.Print("% time spent sending " + (double)_totalSendTicks / elapsedTicks * 100);

            }
        }
    }
}
